//
//  MainClassTableViewController.m
//  Travelling
//
//  Created by lanou on 15/12/16.
//  Copyright © 2015年 Morrrah. All rights reserved.
//

#import "MainClassTableViewController.h"
#import "StoryTableViewCell.h"
#import "MainHeaderScrollView.h"  //轮播图
#import "MainScrollView.h" //轮播图图片的model
#import "DailyStory.h" //每日精选故事
#import "Story.h" //游记
#import "Tourist.h" //游客
#import "PullRefresh.h" //点击刷新

@interface MainClassTableViewController () <UIGestureRecognizerDelegate>
@property (nonatomic,strong) NSMutableArray *headImageArr; //轮播图图片信息数组
@property (nonatomic,strong) NSString *nextStart; //上拉刷新(拼接url)
@property (nonatomic,strong) MainHeaderScrollView *mainHeader;  //推荐轮播图
@property (nonatomic,strong) AppDelegate *myDelegate;
@property (nonatomic,strong) NSMutableArray *storyArr;  //section=1时的数据
@property (nonatomic,strong) NSMutableArray *dailyStoryArr; //section=0时的数据
@property (nonatomic,strong) UIPageControl *pageVC;  //
@property (nonatomic,strong) NSMutableArray *titleArr; //section上的title
@property (nonatomic,strong) PullRefresh *pullRefresh; //点击刷新
@end

@implementation MainClassTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _myDelegate = [UIApplication sharedApplication].delegate;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[StoryTableViewCell class] forCellReuseIdentifier:@"story"];
    [self jsonMainViewWithUrl];
   
}

- (void)setHeaderScrollView
{
    NSMutableArray *imageUrlArr = [NSMutableArray array];
    for (MainScrollView *mainScrollView in _headImageArr) {
        [imageUrlArr addObject:mainScrollView.image_url ];
    }
    _mainHeader = [[MainHeaderScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 170 * _myDelegate.autoSizeScaleY) target:self action:@selector(tapHeadImage) imageArray:imageUrlArr timer:3.5 selector:@selector(autoHeadImage)];
    _pageVC = [[UIPageControl alloc]init];
    _pageVC.numberOfPages = imageUrlArr.count;
    _pageVC.currentPage = 0;
    _pageVC.center = CGPointMake(ScreenWidth / 2.0, 170 * _myDelegate.autoSizeScaleY - 15);
    self.tableView.tableHeaderView = _mainHeader;
    _pullRefresh = [[PullRefresh alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(loadData)];
    _pullRefresh.loadView.userInteractionEnabled = YES;
    [_pullRefresh.loadView addGestureRecognizer:tap];
    self.tableView.tableFooterView = _pullRefresh.loadView;
    [self.view addSubview:_pageVC];
}

- (void)tapHeadImage
{
    
}

// 自动轮播
- (void)autoHeadImage
{
    CGFloat flag = _mainHeader.contentOffset.x;
    if (flag  > ScreenWidth * (_headImageArr.count - 1)) {
        [_mainHeader setContentOffset:CGPointMake(0, 0) animated:NO];
        [_mainHeader setContentOffset:CGPointMake(ScreenWidth, 0) animated:YES];
    }
    else {
        [_mainHeader setContentOffset:CGPointMake(ScreenWidth + flag, 0) animated:YES];
    }
    _pageVC.currentPage = _mainHeader.contentOffset.x / ScreenWidth;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat flag = _mainHeader.contentOffset.x;
    if (flag > ScreenWidth * (_headImageArr.count - 1)) {
        [_mainHeader setContentOffset:CGPointMake(0, 0)];
    }
    if (flag == 0) {
        [_mainHeader setContentOffset:CGPointMake(_headImageArr.count * ScreenWidth, 0)];
    }
    _pageVC.currentPage = _mainHeader.contentOffset.x / ScreenWidth - 1;
}

- (void)jsonMainViewWithUrl
{
    [LORequestManger GET:MainUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        _titleArr = [NSMutableArray array];
        _storyArr = [NSMutableArray array];
        _dailyStoryArr = [NSMutableArray array];
        _headImageArr = [NSMutableArray array];
        NSArray *arr = dic[@"data"][@"elements"];
        NSArray *arrs = arr[0][@"data"][0];
        _nextStart = [[[NSNumberFormatter alloc]init] stringFromNumber:dic[@"data"][@"next_start"]];
        for (NSDictionary *d in arrs) {
            MainScrollView *mainScrollView = [[MainScrollView alloc]init];
            [mainScrollView setValuesForKeysWithDictionary:d];
            [_headImageArr addObject:mainScrollView];
        }
        [_titleArr addObject:arr[1][@"data"][0][@"title"]];
        [_titleArr addObject:arr[6][@"data"][0][@"title"]];
        for (int i = 2; i < 6; i ++) {
            DailyStory *dailyStory = [[DailyStory alloc]init];
            NSDictionary *dic = arr[i][@"data"][0];
            [dailyStory setValuesForKeysWithDictionary:dic];
            [_dailyStoryArr addObject:dailyStory];
        }
        for (int i = 8; i < 27; i ++) {
            if (i != 10 && i != 13) {
                Story *story = [[Story alloc]init];
                NSDictionary *dic = arr[i][@"data"][0];
                [story setValuesForKeysWithDictionary:dic];
                NSDictionary *dicUser = dic[@"user"];
                [story.tourist setValuesForKeysWithDictionary:dicUser];
                [_storyArr addObject:story];
            }
        }
        [self.tableView reloadData];
         [self setHeaderScrollView];
 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    else
    {
        return _storyArr.count;
    }
}

// 区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0 * _myDelegate.autoSizeScaleY;
}

// 区头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]init];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15 * _myDelegate.autoSizeScaleX, 5, ScreenWidth, 25 * _myDelegate.autoSizeScaleY)];
    if (section == 0) {
        titleLabel.text = _titleArr[0];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(ScreenWidth - 40 * _myDelegate.autoSizeScaleX - 15, 5, 40 * _myDelegate.autoSizeScaleX, 25 * _myDelegate.autoSizeScaleY);
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitle:@"更多" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(moreDailyStory) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:button];
    }
    else
    {
        titleLabel.text = _titleArr[1];
    }
    titleLabel.font = [UIFont systemFontOfSize:14.0];
    [headerView addSubview:titleLabel];
    return headerView;
}

// 每日精选点击更多
- (void)moreDailyStory
{
    
}

// 点击刷新
- (void)loadData
{
    self.tableView.tableFooterView = _pullRefresh.loadingView;
    [LORequestManger GET:[NSString stringWithFormat:MainLoadUrl,_nextStart] success:^(id response) {
         NSDictionary *dic = (NSDictionary *)response;
        NSArray *arr = dic[@"data"][@"elements"];
        _nextStart = [[[NSNumberFormatter alloc]init] stringFromNumber:dic[@"data"][@"next_start"]];
        for (NSDictionary *d in arr) {
            NSArray *arrs = d[@"data"];
            Story *story = [[Story alloc]init];
            [story setValuesForKeysWithDictionary:arrs[0]];
            [_storyArr addObject:story];
        }
        [self.tableView reloadData];
        self.tableView.tableFooterView = _pullRefresh.loadView;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

// 首页推荐游记cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    }
    else
    {
    StoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"story"];
        Story *story = _storyArr[indexPath.row];
        cell.story = story;
        return cell;
    }
    
}

// tableview适配高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 200.0;
    }
    else
    {
        return ScreenWidth / 1.78 * _myDelegate.autoSizeScaleY;
    }
}

// 游记选中跳转操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
